package services

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/dao"
	"go_motor_catalog/util"
)

const getYamahaCcUrl = "https://parts.yamaha-motor.co.jp/ypec_b2c/services/omb2c/product_list/"

const getYamahaModelUrl = "https://parts.yamaha-motor.co.jp/ypec_b2c/services/omb2c/model_name_list/"

const getYamahaYearUrl = "https://parts.yamaha-motor.co.jp/ypec_b2c/services/omb2c/model_year_list/"

const getYamahaCatalogUrl = "https://parts.yamaha-motor.co.jp/ypec_b2c/services/omb2c/model_list/"

const yamahaBaseUrl = "https://library.ymcapps.net"

type YamahaOm struct {
}

type YamahaOmRes struct {
	ModelName       string
	ModelYear       string
	CatalogUrl      string
	CatalogShareUrl string
	Desc            string
}

type YamahaOmModel struct {
	dispModelName string `json:"dispModelName"`
	modelName     string `json:"modelName"`
	nickname      string `json:"nickname"`
	productId     string `json:"productId"`
}

func NewYamahaOm() *YamahaOm {
	return &YamahaOm{}
}

func (y *YamahaOm) getModel() []map[string]string {
	res := make([]map[string]string, 0)
	ccParam := map[string]interface{}{
		"baseCode": "6150",
		"langId":   "02",
	}
	ccRes := util.NewHttpUtil().PostResty(getYamahaCcUrl, ccParam)
	ccBody := make(map[string]interface{})
	err := json.Unmarshal(ccRes.Body(), &ccBody)
	if err != nil {
		fmt.Println("获取cc异常", err)
		return res
	}
	ccTypeList := make([]string, 0)
	cc := ccBody["displacementDataCollection"].([]interface{})
	for i := range cc {
		displacement := cc[i].(map[string]interface{})
		productId := fmt.Sprintf("%v", displacement["productId"])
		displacementType := fmt.Sprintf("%v", displacement["displacementType"])
		if productId == "10" {
			if displacementType != "" {
				ccTypeList = append(ccTypeList, displacementType)
			}
		}
	}
	modelParam := map[string]interface{}{
		"baseCode":  "6150",
		"langId":    "02",
		"productId": "10",
	}
	for i := range ccTypeList {
		displacementType := ccTypeList[i]
		modelParam["displacementType"] = displacementType
		modelRes := util.NewHttpUtil().PostResty(getYamahaModelUrl, modelParam)
		modelBody := make(map[string][]map[string]string)
		err := json.Unmarshal(modelRes.Body(), &modelBody)
		if err != nil {
			fmt.Println("获取model异常", err)
			return res
		}
		for m := range modelBody["modelNameDataCollection"] {
			dispModelName := modelBody["modelNameDataCollection"][m]["dispModelName"]
			if dispModelName != "" {
				res = append(res, modelBody["modelNameDataCollection"][m])
			}
		}
	}
	return res
}

func (y *YamahaOm) getYear(model map[string]string) []string {
	res := make([]string, 0)
	param := map[string]interface{}{
		"baseCode":      "6150",
		"destGroupCode": "",
		"destination":   "USA",
		"langId":        "02",
		"modelName":     model["modelName"],
		"nickname":      model["nickname"],
		"productId":     "10",
		"userGroupCode": "AL01",
	}
	yearRes := util.NewHttpUtil().PostResty(getYamahaYearUrl, param)
	yearBody := make(map[string][]map[string]string)
	err := json.Unmarshal(yearRes.Body(), &yearBody)
	if err != nil {
		fmt.Println("获取year异常", err)
	}
	for i := range yearBody["modelYearDataCollection"] {
		year := yearBody["modelYearDataCollection"][i]["modelYear"]
		if year != "" {
			res = append(res, year)
		}
	}
	return res
}

func (y *YamahaOm) getCatalog(model map[string]string, year string) []*YamahaOmRes {
	res := make([]*YamahaOmRes, 0)
	param := map[string]interface{}{
		"baseCode":        "6150",
		"calledCode":      "1",
		"destGroupCode":   "",
		"destination":     "USA",
		"greyModelSign":   false,
		"langId":          "02",
		"modelName":       model["modelName"],
		"modelYear":       year,
		"nickname":        model["nickname"],
		"productId":       "10",
		"publicationLang": "02",
		"useProdCategory": false,
		"userGroupCode":   "AL01",
	}
	catalogRes := util.NewHttpUtil().PostResty(getYamahaCatalogUrl, param)
	catalogBody := make(map[string][]map[string]string)
	err := json.Unmarshal(catalogRes.Body(), &catalogBody)
	if err != nil {
		fmt.Println("获取catalog异常", err)
	}
	for i := range catalogBody["modelDataCollection"] {
		dispModelName := catalogBody["modelDataCollection"][i]["dispModelName"]
		htmlfileURL := catalogBody["modelDataCollection"][i]["htmlfileURL"]
		pdffileURL := catalogBody["modelDataCollection"][i]["pdffileURL"]
		if htmlfileURL == "" && pdffileURL == "" {
			continue
		}
		if htmlfileURL != "" {
			htmlfileURL = yamahaBaseUrl + htmlfileURL
		}
		if pdffileURL != "" {
			pdffileURL = yamahaBaseUrl + pdffileURL
		}
		res = append(res, &YamahaOmRes{
			ModelName:       model["dispModelName"],
			ModelYear:       year,
			Desc:            dispModelName,
			CatalogUrl:      pdffileURL,
			CatalogShareUrl: htmlfileURL,
		})
	}
	return res
}

func (y *YamahaOm) CrawOm(db *gorm.DB) {
	omDao := dao.NewManualModelOmDao(db)
	catalogDao := dao.NewManualCatalogOmDao(db)
	models := y.getModel()
	for i := range models {
		model := models[i]
		years := y.getYear(model)
		for e := range years {
			year := years[e]
			catalogs := y.getCatalog(model, year)
			for c := range catalogs {
				catalog := catalogs[c]
				fmt.Println(model, "-", year, "-", catalog.CatalogUrl)
				modelBean := &dao.ManualModelOm{
					ModelName:       catalog.ModelName,
					ModelNameDetail: "",
					ModelYear:       catalog.ModelYear,
					BrandId:         1,
				}
				catalogBean := &dao.ManualCatalogOm{
					CatalogUrl:      catalog.CatalogUrl,
					CatalogSpareUrl: catalog.CatalogShareUrl,
					CatalogDesc:     catalog.Desc,
				}
				omDao.CreateManualModelOm(modelBean)
				if modelBean.Id == 0 {
					continue
				}
				catalogBean.ModelId = modelBean.Id
				catalogDao.CreateManualCatalogOm(catalogBean)
				fmt.Println(model, "-", year, "-successfull")
			}
		}
	}
}
